import Reflux from 'reflux'
import { UserRegisterAction } from '../actions'
import { Toast } from 'antd-mobile'
import { config,helper,myFetch } from 'appRoot/components/utils'
import cookie from 'react-cookie'

const UserRegisterStore = Reflux.createStore({
	listenables: UserRegisterAction,
	onRegister(data) {
		data.hashedPassword = helper.aesEncrypt(data.password)
		if (data.mobile) {
			data.mobile = data.mobile.replace(/\s/g,'')
		}
		if (data.vCode) {
			data.vCode = data.vCode.replace(/\s/g,'')
		}
		delate data.password
		cookie.load('openId') ? data.openId = cookie.load('openId') : null
		const options = {
			method: 'POST',
			body: JSON.stringify(data),
		}
		//访问地址API等到时候后台做好了  再重新传
		myFetch(`${config.rootApi}/customers/regist/add`, options)
		.then((rs) => {
			if (rs) {
				Toast.hide()
				// 注册成功，通知`HomePage`设置活动`tab`为登录
				Toast.success('注册成功！')
				localStorage.removeItem('memberId')
				if (rs.LoginId) {
					localStorage.setItem('customerId', rs.LogonId)
				}
				this.trigger('login')
			}
		})
		.catch(err => helper.onPromiseError(err))
	},
})

export default UserRegisterStore